package com.serverSite;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.ResultSet;

import org.json.JSONObject;

import com.bdd.ConMySql;
import com.request.Json2Sql;

/**
 * this class more than being a thread, creates connections between the 2 servers
 * and sends json objects
 * @author brunocesi
 *
 */
public class ServerThreadSite implements Runnable{
	private Socket socket;
	private int portServeur;
	private PrintWriter out;
	private BufferedReader in;
	
	public ServerThreadSite(Socket socket, int port){
		this.socket = socket;
		this.portServeur=port;
	}
	public void run() {
		Json2Sql j2s = new Json2Sql();			// a Json to SQL object
		Processing process = new Processing();	// a Prossecing object
		try{
			out = new PrintWriter(socket.getOutputStream(), true);
			InputStreamReader isr=new InputStreamReader(socket.getInputStream());
			in = new BufferedReader(isr);
			while(true)
			{
				while(!in.ready());
				String line = in.readLine();
				JSONObject jsonO = new JSONObject(line);
				
				if(jsonO.getString("message").equals("book")){			//if the json is of 'type' booking
					ConMySql con = new ConMySql("bddSite"+this.portServeur);
					String sql = j2s.requestObject(jsonO);				// create the sql query
					ResultSet rs=con.select(sql);						//request in product table
					jsonO = process.bookingProcess(jsonO, rs, con);		//create the corresponding json and update the database
					out.println(jsonO);
					con.close();
				}
				else if(jsonO.getString("message").equals("buy")){		//if the json is of 'type' buying
					ConMySql con = new ConMySql("bddSite"+this.portServeur);
					String sql = j2s.requestObject(jsonO);				// create the sql query
					ResultSet rs=con.select(sql);						//request in product table
					jsonO = process.buyingProcess(jsonO, rs, con);		//create the corresponding json and update the database
					out.println(jsonO);
					con.close();
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			System.err.println("Thread : "+e.getMessage());
		}
	}
}
